package com.wing.product.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.order.model.entity.CabInventoryProduct;
import com.wing.order.service.CabInventoryProductService;
import com.wing.product.dao.ProductDao;
import com.wing.product.model.entity.*;
import com.wing.system.service.EnterpricceIdService;
import com.wing.web.excel.ProductExcelIn;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductService {

    @Autowired
    private ProductCategoryExtService productCategoryExtService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductDetailAttributeService productDetailAttributeService;

    @Autowired
    private ProductDetailSpecService productDetailAttributeValueService;

    @Autowired
    private ProductBrandService productBrandService;

    @Autowired
    private EnterpricceIdService enterpricceIdService;

    @Autowired
    private CabInventoryProductService cabInventoryProductService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProcessLineTemplateService processLineTemplateService;

    @Autowired
    private ProcessLineTemplateRecordService processLineTemplateRecordService;

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private DictLabelService dictLabelService;

    @Override
    @Transactional
    public void add(Product productParam) throws Exception {
        //添加产品
        QueryWrapper<Product> productWrapper = new QueryWrapper<>();
        productWrapper.eq("product_code", productParam.getProductCode());
        List<Product> productList = this.list(productWrapper);
        if (productList.size() > 0) {
            throw new BusinessException("货品编码已存在！");
        }
        productParam.setCreator(JwtUtils.getLoginUserId());
        productParam.setCreatorName(JwtUtils.getLoginUsername());
        //工艺线路-工序列表
        List<ProcessLineTemplateRecord> processLineTemplateRecordList = processLineTemplateRecordService.list();
        //SKU工序集
        List<ProcessLineTemplateRecord> recordList = processLineTemplateRecordList.stream().filter(t -> t.getProcessLineTemplateId().longValue() == productParam.getProductProcessLineId().longValue()).collect(Collectors.toList());
        String skuProcessCode = "";
        for (int k = 0; k < recordList.size(); k++) {
            if (k == 0) {
                skuProcessCode = recordList.get(k).getProcessId() + "";
            } else {
                skuProcessCode += "," + recordList.get(k).getProcessId();
            }
        }
        productParam.setSkuProcessCode(skuProcessCode);
        baseMapper.insert(productParam);

        //添加添加SKU
        List<ProductDetail> productDetailList = productParam.getProductDetailList();
        List<ProductDetail> deatilList = new ArrayList<ProductDetail>();

        //判断SKU编号是否有重复
        List newList = productDetailList.stream().map(ProductDetail::getSkuCode).distinct().collect(Collectors.toList());
        if (newList.size() != productDetailList.size()) {
            throw new BusinessException("SKU编码重复");
        }

        //判断商品规格是否有重复
        newList = productDetailList.stream().map(ProductDetail::getSkuSpec).distinct().collect(Collectors.toList());
        if (newList.size() != productDetailList.size()) {
            throw new BusinessException("商品规格重复");
        }

        for (ProductDetail productDetail : productDetailList) {
            //监测skuCode是否存在，保证唯一
            QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("sku_code", productDetail.getSkuCode());
            List<ProductDetail> productDetails = productDetailService.list(wrapper);
            if (productDetails.size() > 0) {
                throw new BusinessException("产品SKU编码已存在！");
            }
            productDetail.setProductId(productParam.getId());
            productDetail.setProductCategoryId(productParam.getProductCategoryId());
            productDetail.setProductTypeId(productParam.getProductTypeId());
            productDetail.setMaterialNature(productParam.getMaterialNature());
            productDetail.setPricingMethod(productParam.getCalculateWay());
            productDetail.setProductProcessLineId(productParam.getProductProcessLineId());
            productDetail.setSkuProcessCode(productParam.getSkuProcessCode());
            productDetailService.getBaseMapper().insert(productDetail);
            //新增产品库存记录
            CabInventoryProduct cabInventoryProduct = new CabInventoryProduct();
            cabInventoryProduct.setSkuId(productDetail.getId());
            cabInventoryProduct.setSkuCode(productDetail.getSkuCode());
            cabInventoryProduct.setQuantity(0);
            cabInventoryProduct.setSkuType(0);
            cabInventoryProduct.setSourceType(0);
            cabInventoryProduct.setType(CabInventoryProduct.Type.make);
            cabInventoryProductService.save(cabInventoryProduct);
        }
    }

    @Override
    public List<Product> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<Product> pageList4app(Page page, Map<String, Object> params) {
        List<Product> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Product get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void deleteProductById(Long productId) {
        baseMapper.deleteById(productId);

        QueryWrapper<ProductDetail> detailQueryWrapper = new QueryWrapper<ProductDetail>();
        detailQueryWrapper.eq("product_id", productId);
        List<ProductDetail> detailList = productDetailService.list(detailQueryWrapper);
        productDetailService.deleteProductDetailByProductId(productId);

        //删除库存表记录
        for (ProductDetail productDetail : detailList) {
            QueryWrapper<CabInventoryProduct> cabInventoryProductQueryWrapper = new QueryWrapper<CabInventoryProduct>();
            cabInventoryProductQueryWrapper.eq("sku_code", productDetail.getSkuCode());
            cabInventoryProductService.remove(cabInventoryProductQueryWrapper);
        }
    }

    @Override
    @Transactional
    public void updateProductById(Product productParam) throws Exception {
        //更新产品
        Product product = baseMapper.selectById(productParam.getId());
        if (product == null) {
            throw new BusinessException("没有此货品");
        }
        baseMapper.updateById(productParam);
        //更新产品明细
        productDetailService.deleteProductDetailByProductId(product.getId());
        List<ProductDetail> detailFormList = productParam.getProductDetailList();
        List<ProductDetail> deatilList = new ArrayList<ProductDetail>();
        for (ProductDetail productDetailForm : detailFormList) {
            //监测skuCode是否存在，保证唯一
            QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("sku_code", productDetailForm.getSkuCode());
            List<ProductDetail> productDetailList = productDetailService.list(wrapper);
            if (productDetailList.size() > 0) {
                throw new BusinessException("产品SKU编码已存在！");
            }
            deatilList.add(productDetailForm);
        }
        productDetailService.saveBatch(deatilList);
    }

    @Override
    @Transactional
    public void batchAddProduct(List<Product> productList) throws Exception {
        for (Product product : productList) {
            //添加产品
            QueryWrapper<Product> productWrapper = new QueryWrapper<>();
            productWrapper.eq("product_code", product.getProductCode());
            List<Product> productDbList = this.list(productWrapper);
            if (productDbList.size() > 0) {
                throw new BusinessException("产品编码已存在！");
            }
            this.baseMapper.insert(product);

            List<ProductDetail> productDetailList = product.getProductDetailList();
            //判断SKU编号是否有重复
            List newList = productDetailList.stream().map(ProductDetail::getSkuCode).distinct().collect(Collectors.toList());
            if (newList.size() != productDetailList.size()) {
                throw new BusinessException("产品SKU编码重复！");
            }
            for (ProductDetail productDetail : productDetailList) {
                //监测skuCode是否存在，保证唯一
                QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("sku_code", productDetail.getSkuCode());
                List<ProductDetail> productDetailDbList = productDetailService.list(wrapper);
                if (productDetailDbList.size() > 0) {
                    throw new BusinessException("产品SKU编码已存在！");
                }
                productDetail.setCreator(JwtUtils.getLoginUserId());
                productDetail.setCreatorName(JwtUtils.getLoginUsername());
                productDetailService.save(productDetail);
                //新增库存信息
                CabInventoryProduct cabInventoryProduct = new CabInventoryProduct();
                cabInventoryProduct.setSkuId(productDetail.getId());
                cabInventoryProduct.setSkuCode(productDetail.getSkuCode());
                cabInventoryProduct.setQuantity(0);
                cabInventoryProduct.setSkuType(0);
                cabInventoryProduct.setSourceType(0);
                cabInventoryProduct.setType(CabInventoryProduct.Type.make);
                cabInventoryProductService.save(cabInventoryProduct);

            }
        }
    }

    @Override
    public void importExcel(List<ProductExcelIn> list) {
        //所有产品信息
        List<Product> productAllList = this.baseMapper.selectList(null);
        //工艺线路模板列表
        List<ProcessLineTemplate> processLineTemplateList = processLineTemplateService.list();
        //工艺线路-工序列表
        List<ProcessLineTemplateRecord> processLineTemplateRecordList = processLineTemplateRecordService.list();
        //物料分类列表
        QueryWrapper<ProductCategory> productCategoryQueryWrapper = new QueryWrapper<>();
        productCategoryQueryWrapper.eq("is_final", 1);
        List<ProductCategory> productCategoryList = productCategoryService.list(productCategoryQueryWrapper);
        //物料类别
        QueryWrapper<ProductType> productTypeQueryWrapper = new QueryWrapper<>();
//        productTypeQueryWrapper.eq("final_classify_status", 0);
        List<ProductType> productTypeList = productTypeService.list(productTypeQueryWrapper);
        //品牌
        QueryWrapper<ProductBrand> productBrandQueryWrapper = new QueryWrapper<>();
        List<ProductBrand> productBrandList = productBrandService.list(productBrandQueryWrapper);
        //字典数据
        List<DictLabel> dictLabelList = dictLabelService.list(null);

        List<Product> productList = new ArrayList<>();

        int i = 1;
        for (ProductExcelIn product : list) {
            if (StringUtils.isBlank(product.getProductName())) {
                throw new BusinessException(300, "第" + i + "行【货品名称】未输入数据");
            }
            if (StringUtils.isBlank(product.getProductCode())) {
                throw new BusinessException(300, "第" + i + "行【货品编码】未输入数据");
            }
            if (StringUtils.isBlank(product.getMaterialNature())) {
                throw new BusinessException(300, "第" + i + "行【物料类别性质】未输入数据");
            }
            if (StringUtils.isBlank(product.getProductType())) {
                throw new BusinessException(300, "第" + i + "行【所属类别】未输入数据");
            }
            if (StringUtils.isBlank(product.getProductCategory())) {
                throw new BusinessException(300, "第" + i + "行【物料分类】未输入数据");
            }
            if (StringUtils.isBlank(product.getBaseUnit())) {
                throw new BusinessException(300, "第" + i + "行【基础单位】未输入数据");
            }
            i++;

            //判断料号是否存在
            Product product0 = productAllList.stream().filter(t -> t.getProductCode().equals(product.getProductCode())).findFirst().orElse(null);
            if (product0 != null) {
                throw new BusinessException(300, "货品编码[" + product.getProductCode() + "]已存在");
            }
            Product p = new Product();
            p.setName(product.getProductName());
            p.setProductCode(product.getProductCode());
            p.setHistoryName(product.getHistoryProductName());
            p.setHistoryProductCode(product.getHistoryProductCode());
            p.setSpecCode(product.getSpecCode());
            //物料类别性质
            DictLabel materialNature = dictLabelList.stream().filter(t -> "sys_product_type_nature".equals(t.getDictType()) && product.getMaterialNature().equals(t.getLabelName())).findFirst().orElse(null);
            p.setMaterialNature(materialNature.getLabelValue());
            //所属类别
            ProductType productType = productTypeList.stream().filter(t -> product.getProductType().equals(t.getName())).findFirst().orElse(null);
            p.setProductTypeId(productType.getId());
            //物料分类
            ProductCategory productCategory = productCategoryList.stream().filter(t -> t.getName().equals(product.getProductCategory())).findFirst().orElse(null);
            p.setProductCategoryId(productCategory.getId());
            //库存计量方式
            DictLabel calculateWay = dictLabelList.stream().filter(t -> "sys_product_detail_calculate_way".equals(t.getDictType()) && product.getCalculateWay().equals(t.getLabelName())).findFirst().orElse(null);
            p.setCalculateWay(calculateWay.getLabelValue());
            //基础单位
            DictLabel baseUnit = dictLabelList.stream().filter(t -> "sys_product_detail_base_unit".equals(t.getDictType()) && product.getBaseUnit().equals(t.getLabelName())).findFirst().orElse(null);
            p.setBaseUnit(baseUnit.getLabelValue());
            p.setSelfProductStatus("是".equals(product.getSelfProductStatus()) ? "0" : "1");
            p.setOutsourceStatus("是".equals(product.getOutsourceStatus()) ? "0" : "1");
            //工艺线路
            if (StringUtils.isNotBlank(product.getProductProcessLine())) {
                ProcessLineTemplate processLineTemplate = processLineTemplateList.stream().filter(t -> t.getName().equals(product.getProductProcessLine())).findFirst().orElse(null);
                p.setProductProcessLineId(processLineTemplate.getId());
                //SKU工序集
                List<ProcessLineTemplateRecord> recordList = processLineTemplateRecordList.stream().filter(t -> t.getProcessLineTemplateId().longValue() == processLineTemplate.getId()).collect(Collectors.toList());
                String skuProcessCode = "";
                for (int k = 0; k < recordList.size(); k++) {
                    if (k == 0) {
                        skuProcessCode = recordList.get(k).getProcessId() + "";
                    } else {
                        skuProcessCode += "," + recordList.get(k).getProcessId();
                    }
                }
                p.setSkuProcessCode(skuProcessCode);
            }
            p.setSellStatus("是".equals(product.getSellStatus()) ? "0" : "1");
            p.setWarningQuantity(Integer.valueOf(product.getSafeStockValue()));
            p.setLethargyThreshold(Integer.valueOf(product.getDullTimeValue()));
            p.setWarrantyDay(Integer.valueOf(product.getWarrantyDay()));
            p.setDepreciationTime(Integer.valueOf(product.getDepreciationTime()));
            //数据来源
            DictLabel dataSource = dictLabelList.stream().filter(t -> "sys_product_detail_data_source".equals(t.getDictType()) && product.getDataSource().equals(t.getLabelName())).findFirst().orElse(null);
            p.setDataSource(dataSource.getLabelValue());
            p.setThingCodeStatus("是".equals(product.getThingCodeStatus()) ? "0" : "1");
            p.setBatchStatus("是".equals(product.getBatchStatus()) ? "0" : "1");
            p.setInoutStatus("是".equals(product.getInoutStatus()) ? "0" : "1");
            p.setRemark(product.getRemark());
            productList.add(p);
        }
        this.saveBatch(productList);
    }
}
